package com.yy.utils.exception;

import java.sql.SQLException;

import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.alibaba.fastjson.JSONException;
import com.yy.utils.ResponseEntity;


/**
 * 异常处理器
 * 
 * @author 
 * @date 
 */
@RestControllerAdvice
public class RRExceptionHandler {
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	/**

	 * 自定义异常

	 */
	@ExceptionHandler(RRException.class)
	public ResponseEntity handleRRException(RRException e){
		ResponseEntity r = new ResponseEntity();
		r.put("code", e.getCode());
		r.put("msg", e.getMessage());

		return r;
	}

	@ExceptionHandler(DuplicateKeyException.class)
	public ResponseEntity handleDuplicateKeyException(DuplicateKeyException e){
		logger.error(e.getMessage(), e);
		return ResponseEntity.error("数据库中已存在该记录");
	}

	@ExceptionHandler(AuthorizationException.class)
	public ResponseEntity handleAuthorizationException(AuthorizationException e){
		logger.error(e.getMessage(), e);
		return ResponseEntity.error("没有权限，请联系管理员授权");
	}

	@ExceptionHandler(Exception.class)
	public ResponseEntity handleException(Exception e){
		logger.error(e.getMessage(), e);
		return ResponseEntity.error();
	}
	
	@ExceptionHandler(JSONException.class)
	public ResponseEntity jsonException(JSONException e){
		logger.error(e.getMessage(), e);
		logger.error("json数据格式不符合Entity格式");
		return ResponseEntity.error("数据类型错误");
	}
	
	@ExceptionHandler(DataIntegrityViolationException.class)
	public ResponseEntity dataIntegrityViolationException(DataIntegrityViolationException e){
		logger.error(e.getMessage(), e);
		logger.error("Insert或Update数据时违反了完整性，例如违反了惟一性限制");
		return ResponseEntity.error("数据格式错误");
	}
	
	@ExceptionHandler(NullPointerException.class)
	public ResponseEntity nullPointerException(NullPointerException e){
		logger.error(e.getMessage(), e);
		return ResponseEntity.error("数据为空");
	}

}
